<?php

namespace App\Console\Commands;

use App\Http\Services\common\WxService;
use App\Models\MemoModel;
use App\Models\RemindModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WechatReminder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wx_reminder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '微信提醒:每分钟执行';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $time = date('Y-m-d H:i', time());
        $remindArr = RemindModel::query()->with(['memos', 'user'])
            ->where('sent_time', '>=', $time)
            ->where('reminder_status', '=', 0)
            ->get()->toArray();

        if (!empty($remindArr)) {
            $wxService = new WxService();
            foreach ($remindArr as $value) {
                $sendTime = date('Y-m-d H:i', strtotime($value['sent_time']));
                // 到时间时发送提醒
                if($sendTime == $time){
                    $sentData = [
                        'thing1' => [
                            $value['memos']['title']
                        ],
                        'thing2' => [
                            'value' => $value['memos']['desc']
                        ],
                        'phrase4' => [
                            'value' => $value['memos']['priority'] == 1 ? '重要' : '一般'
                        ],
                        'time3' => [
                            'value' => $value['memos']['date']
                        ]
                    ];
                    $response = $wxService->sendSubscribeMessage($value['user']['openid'], $sentData, $value['memos']['id']);
                    if ($response['errcode'] == 0) {
                        DB::transaction(function () use ($value) {
                            RemindModel::query()->where('id', $value['id'])->update(['reminder_status' => 1]);
                            MemoModel::query()->where('id', $value['memos']['id'])->update(['status' => 1]);
                        });
                        $this->info($value['user']['openid'] . '发送成功');
                    }else{
                        Log::channel('wechatlog')->info('发送失败', ['response' => $response,'openid' => $value['user']['openid']]);
                        $this->info($value['user']['openid'] . '发送失败：'.json_encode($response));
                    }
                }else{
                    Log::channel('wechatlog')->info('未到时间', ['sent_time' => $sendTime,'time' => $time,'openid' => $value['user']['openid']]);
                }
            }
        }
    }
}
